#ifndef WEBRTCWIDGET_H
#define WEBRTCWIDGET_H

#include <QWidget>
#include "abstractwebview.h"
#include "public/VideoBase.h"
#include <QObject>
#include <QNetworkAccessManager>
#include <QTimer>
#include <QLabel>
#include <QPushButton>
#include <QFile>

// WebRTC桥接类
class WebRTCBridge : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QString serverUrl READ serverUrl WRITE setServerUrl NOTIFY serverUrlChanged)

public:
    explicit WebRTCBridge(QObject *parent = nullptr);
    ~WebRTCBridge();

    QString serverUrl() const { return m_serverUrl; }
    void setServerUrl(const QString &url) {
        if(url != "" && m_serverUrl != url)
        {
            m_serverUrl = url;
            emit serverUrlChanged(url);
        }
    }

public slots:
    void sendOffer(const QString &offer);
    void updateConnectionState(const QString &state);
    void saveRecording(const QString &base64Data);
    void startRecording();
    void stopRecording();

signals:
    void offerResponse(const QString &response);
    void connectionStateChanged(const QString &state);
    void serverUrlChanged(const QString &url);
    void recordingSaved(const QString &filePath);
    void recordingError(const QString &error);

private:
    QNetworkAccessManager *networkManager;
    QString m_serverUrl;
    QFile* m_recordingFile = nullptr;
    QString m_currentRecordingPath;
};

class MainWindow;

class WebRTCWidget : public VideoBase
{
    Q_OBJECT
protected:
    explicit WebRTCWidget(QWidget *parent = nullptr);
    ~WebRTCWidget();
    void setUrl(QString strUrl);
    friend class MainWindow;
private:
    void stopVideo(bool bSync);
    void takePhoto();
    bool startRecording();
    bool stopRecording(bool bSync);
    void initWebView();
    void setupConnections();
    void startPlay();
    void setMute(bool bMute);
public slots:
    void onLoadFinished(bool ok);

private:
    AbstractWebView *m_pWebView;
    WebRTCBridge *m_pWebrtcBridge;
    QLabel * m_pMask; //覆盖在上层，父窗口才能响应到点击

    // QWidget interface
protected:
    void resizeEvent(QResizeEvent *event);

    // VideoBase interface
protected:
};

#endif // WEBRTCWIDGET_H
